#include "xgameengine.h"

XGameEngine::XGameEngine()
{
    //ctor
}

XGameEngine::~XGameEngine()
{
    //dtor
}

bool XGameEngine::init(int width, int height)
{
    getGameWindow().Create(sf::VideoMode(width, height), "The Legend of Sword");
    getGameWindow().SetFramerateLimit(60);
    getGameWindow().SetActive(true);
    return getGameWindow().IsOpened();
}

void XGameEngine::draw()
{
    getGameWindow().Clear();

    getGameWindow().Display();
}

void XGameEngine::update()
{

}

void XGameEngine::handleEvent()
{

    if (!m_states.empty())
    {
        m_states.back()->handleEvent(this);
    }
    else
    {
        sf::Event event;
        while(getGameWindow().PollEvent(event))
        {
            // Request for closing the window
            if (event.Type == sf::Event::Closed)
                getGameWindow().Close();
        }
    }
}

void XGameEngine::changeState(XGameState* pState)
{
    // Cleanup the current state
    if(!m_states.empty())
    {
        m_states.back()->cleanup(this);
        m_states.pop_back();
    }

    // Store and init the new state
    m_states.push_back(pState);
    m_states.back()->init(this);
}

void XGameEngine::pushState(XGameState* pState)
{
    // Pause current state
    if(!m_states.empty())
    {
        m_states.back()->pause(this);
    }

    // Store and init the new state
    m_states.push_back(pState);
    m_states.back()->init(this);
}

void XGameEngine::popState()
{
    // Cleanup the current state
    if (!m_states.empty())
    {
        m_states.back()->cleanup(this);
        m_states.pop_back();
    }

    // Resume previous state
    if(!m_states.empty())
    {
        m_states.back()->resume(this);
    }
}

void XGameEngine::cleanup()
{

}

void XGameEngine::quit()
{
    m_gameWindow.Close();
}

bool XGameEngine::isRunning() const
{
    return m_gameWindow.IsOpened();
}

sf::RenderWindow& XGameEngine::getGameWindow()
{
    return m_gameWindow;
}

const sf::Input& XGameEngine::getGameInput()
{
    return getGameWindow().GetInput();
}
